import { track, trigger } from './effect'

const isObject = (value) => value !== null && typeof value === 'object'

export const reactive = <T extends object>(target: T) => {
  return new Proxy(target, {
    get(target, key, receiver) {
      const res = Reflect.get(target, key, receiver) as object // 保证上下文正确
      track(target, key)
      if (isObject(res)) return reactive(res)
      return res
    },

    set(target, key, value, receiver) {
      const res = Reflect.set(target, key, receiver) // 保证上下文正确
      trigger(target, key)
      return res
    },
  })
}
